//
//  AppDelegate.m
//  qianke
//
//  Created by ZX on 2017/6/23.
//  Copyright © 2017年 ZX. All rights reserved.
//

#import "AppDelegate.h"
#import "ZXTabBarController.h"
#import "choseRoleController.h"
#import "ZXNavigationController.h"

#import <objc/runtime.h>
#import "XGPush.h"
#import "XGSetting.h"
#import "ZXLoginRegisterViewController.h"
#import <CoreLocation/CoreLocation.h>
#ifdef NSFoundationVersionNumber_iOS_9_x_Max
#import <UserNotifications/UserNotifications.h>
#endif
@interface AppDelegate ()<UNUserNotificationCenterDelegate,CLLocationManagerDelegate>
// 区域监听
/**  位置管理者 */
@property (nonatomic, strong) CLLocationManager *manager;
@end

@implementation AppDelegate


- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {
    NSLogfun;
    self.window = [[UIWindow alloc]initWithFrame:[UIScreen mainScreen].bounds];
    ZXLoginRegisterViewController* loginVc = [ZXLoginRegisterViewController new];
        self.window.rootViewController = loginVc;
    [self.window makeKeyAndVisible];
//    [self getLcation];
//    [self setPust];
    if (!_roleArr) {
        _roleArr = [NSMutableArray arrayWithObjects:@0,@1,@2,@3,@4,@5,nil];
    }
    return YES;
}

-(void)time{
    _MonthBeginTime = [ZXToolObj getMonthBeginWith:[NSString stringWithFormat:@"2017-%@",[ZXToolObj getLastMonth]]];
    _MonthEndTime = [ZXToolObj getMonthEndWith:[NSString stringWithFormat:@"2017-%@",[ZXToolObj getLastMonth]]];
    _thisMonthBeginTime = [ZXToolObj getMonthBeginWith:[NSString stringWithFormat:@"2017-%@",[ZXToolObj getMonth]]];
    _thisMonthEndTime = [ZXToolObj getMonthEndWith:[NSString stringWithFormat:@"2017-%@",[ZXToolObj getMonth]]];
}
#pragma mark -- 本地通知

-(void)setLocalPush{
    UILocalNotification *localNotifi = [UILocalNotification new];
    [[UIApplication sharedApplication] scheduleLocalNotification:localNotifi];
    localNotifi.fireDate = [NSDate dateWithTimeIntervalSinceNow:30];
    localNotifi.soundName = UILocalNotificationDefaultSoundName;
    localNotifi.alertBody = @"今天不适合敲代码";
    //    settingsForTypes 通知需要更改的东西，可以修改多个地方，UIUserNotificationType 枚举：
    //    UIUserNotificationTypeNone    = 0,
    //    UIUserNotificationTypeBadge   = 1 << 0, //图标标记
    //    UIUserNotificationTypeSound   = 1 << 1, //声音
    //    UIUserNotificationTypeAlert   = 1 << 2, //提醒
    UIUserNotificationSettings *settings = [UIUserNotificationSettings settingsForTypes:UIUserNotificationTypeBadge | UIUserNotificationTypeSound | UIUserNotificationTypeAlert categories:nil];
    [[UIApplication sharedApplication] registerUserNotificationSettings:settings];
//    [[UIApplication sharedApplication] presentLocalNotificationNow:localNotifi];
//    [[UIApplication sharedApplication] scheduleLocalNotification:localNotifi];
    
    UNUserNotificationCenter *center = [UNUserNotificationCenter currentNotificationCenter];
    [center requestAuthorizationWithOptions:(UNAuthorizationOptionBadge | UNAuthorizationOptionSound | UNAuthorizationOptionAlert) completionHandler:^(BOOL granted, NSError * _Nullable error) {
        if (!error) {
            NSLog(@"request authorization succeeded!");
        }
    }];
    UNMutableNotificationContent *content = [[UNMutableNotificationContent alloc] init];
    content.title = @"Introduction to Notifications";
    content.subtitle = @"Session 7007";
    content.body = @"Woah! These new notifications look amazing! Don’t you agree?";
//    content.badge = @1;
//    UNTimeIntervalNotificationTrigger *trigger1 = [UNTimeIntervalNotificationTrigger triggerWithTimeInterval:6000 repeats:YES];
//    NSString *requestIdentifier = @"sampleRequest";
//    UNNotificationRequest *request = [UNNotificationRequest requestWithIdentifier:requestIdentifier content:content trigger:trigger1];
//    [center addNotificationRequest:request withCompletionHandler:^(NSError * _Nullable error) { }];

}
-(void)userNotificationCenter:(UNUserNotificationCenter *)center willPresentNotification:(UNNotification *)notification withCompletionHandler:(void (^)(UNNotificationPresentationOptions))completionHandler{
    
    completionHandler(UNNotificationPresentationOptionAlert | UNNotificationPresentationOptionSound);
    
}
#pragma mark --xgpush
-(void)setPust{
    [[XGSetting getInstance] enableDebug:YES];
    [XGPush startApp:2200261739 appKey:@"I7L4684VSIDZ"];
    [XGPush isPushOn:^(BOOL isPushOn) {
        NSLog(@"[XGDemo] Push Is %@", isPushOn ? @"ON" : @"OFF");
    }];
    
    [self registerAPNS];
    
}
- (void)application:(UIApplication *)application didRegisterForRemoteNotificationsWithDeviceToken:(NSData *)deviceToken{
    NSString *deviceTokenStr = [XGPush registerDevice:deviceToken
                                              account:nil
                                      successCallback:^{
                                          NSLog(@"[XGPush Demo] register push success");
                                      } errorCallback:^{
                                          NSLog(@"[XGPush Demo] register push error");
                                      }];
    NSLog(@"[XGPush Demo] device token is %@", deviceTokenStr);
}


//点击通知进入应用 <iOS10
- (void)application:(UIApplication *)application
didReceiveRemoteNotification:(NSDictionary *)userInfo{
    NSLog(@"[XGPush Demo] receive Notification");
    [XGPush handleReceiveNotification:userInfo
                      successCallback:^{
                          NSLog(@"[XGDemo] Handle receive success");
                      } errorCallback:^{
                          NSLog(@"[XGDemo] Handle receive error");
                      }];
}
//点击通知进入应用 >iOS10
-(void)userNotificationCenter:(UNUserNotificationCenter *)center didReceiveNotificationResponse:(UNNotificationResponse *)response withCompletionHandler:(void (^)(void))completionHandler{
    [XGPush handleReceiveNotification:response.notification.request.content.userInfo
                      successCallback:^{
                          NSLog(@"[XGDemo] Handle receive success");
                      } errorCallback:^{
                          NSLog(@"[XGDemo] Handle receive error");
                      }];
    NSLog(@"response.notification.request.content.userInfo==%@",response.notification.request.content.userInfo);
    NSLog(@"response==%@",response);
    
    completionHandler();
    
}


//- (void)userNotificationCenter:(UNUserNotificationCenter *)center
//didReceiveNotificationResponse:(UNNotificationResponse *)response
//         withCompletionHandler:(void(^)(void))completionHandler{
//    
//    [XGPush handleReceiveNotification:response.notification.request.content.userInfo
//                      successCallback:^{
//                          NSLog(@"[XGDemo] Handle receive success");
//                      } errorCallback:^{
//                          NSLog(@"[XGDemo] Handle receive error");
//                      }];
//    NSLog(@"response.notification.request.content.userInfo==%@",response.notification.request.content.userInfo);
//    NSLog(@"response==%@",response);
//    
//    completionHandler();
//    
//}
- (void)registerAPNS {
    float sysVer = [[[UIDevice currentDevice] systemVersion] floatValue];
#if __IPHONE_OS_VERSION_MAX_ALLOWED >= __IPHONE_10_0
    if (sysVer >= 10) {
        // iOS 10
        [self registerPush10];
    } else if (sysVer >= 8) {
        // iOS 8-9
        [self registerPush8to9];
    } else {
        // before iOS 8
//        [self registerPushBefore8];
    }
#else
    if (sysVer < 8) {
        // before iOS 8
        [self registerPushBefore8];
    } else {
        // iOS 8-9
        [self registerPush8to9];
    }
#endif
}

- (void)registerPush10{
#if __IPHONE_OS_VERSION_MAX_ALLOWED >= __IPHONE_10_0
    UNUserNotificationCenter *center = [UNUserNotificationCenter currentNotificationCenter];
    center.delegate = self;
    
    [center requestAuthorizationWithOptions:UNAuthorizationOptionBadge | UNAuthorizationOptionSound | UNAuthorizationOptionAlert completionHandler:^(BOOL granted, NSError * _Nullable error) {
        if (granted) {
        }
    }];
    [[UIApplication sharedApplication] registerForRemoteNotifications];
    //Local Notification
//    UNMutableNotificationContent *content = [[UNMutableNotificationContent alloc] init];
//    content.title = @"Introduction to Notifications";
//    content.subtitle = @"Session 707";
//    content.body = @"Woah! These new notifications look amazing! Don’t you agree?";
//    content.badge = @1;
#endif
}

- (void)registerPush8to9{
    UIUserNotificationType types = UIUserNotificationTypeBadge | UIUserNotificationTypeSound | UIUserNotificationTypeAlert;
    UIUserNotificationSettings *mySettings = [UIUserNotificationSettings settingsForTypes:types categories:nil];
    [[UIApplication sharedApplication] registerUserNotificationSettings:mySettings];
    [[UIApplication sharedApplication] registerForRemoteNotifications];
}

- (void)registerPushBefore8{
//    [[UIApplication sharedApplication] registerForRemoteNotificationTypes:(UIRemoteNotificationTypeAlert | UIRemoteNotificationTypeBadge | UIRemoteNotificationTypeSound)];
}
#pragma mark --location
-(void)getLcation{
    self.manager = [[CLLocationManager alloc] init];
    self.manager.delegate = self;
    [self.manager requestAlwaysAuthorization];
    [self.manager startUpdatingLocation];
}
-(void)locationManager:(nonnull CLLocationManager *)manager didUpdateLocations:(nonnull NSArray<CLLocation * > *)locations
{
    CLLocation *newLocation = [locations lastObject];
    my_AppDelegate.myLatitude = newLocation.coordinate.latitude;
    my_AppDelegate.myLongitude = newLocation.coordinate.longitude;
    
    [[NSUserDefaults standardUserDefaults] setFloat:my_AppDelegate.myLatitude  forKey:my_Latitude];
    [[NSUserDefaults standardUserDefaults] synchronize];
    [[NSUserDefaults standardUserDefaults] setFloat:my_AppDelegate.myLongitude forKey:my_Longitude];
    [[NSUserDefaults standardUserDefaults] synchronize];
//    NSLog(@"每当请求到位置信息时, 都会调用此方法\n%f\n%f",newLocation.coordinate.latitude,newLocation.coordinate.longitude);
}
- (void)applicationWillResignActive:(UIApplication *)application {
    NSLog(@"进入不活跃状态");
    // Sent when the application is about to move from active to inactive state. This can occur for certain types of temporary interruptions (such as an incoming phone call or SMS message) or when the user quits the application and it begins the transition to the background state.
    // Use this method to pause ongoing tasks, disable timers, and invalidate graphics rendering callbacks. Games should use this method to pause the game.
}


- (void)applicationDidEnterBackground:(UIApplication *)application {
    // Use this method to release shared resources, save user data, invalidate timers, and store enough application state information to restore your application to its current state in case it is terminated later.
    // If your application supports background execution, this method is called instead of applicationWillTerminate: when the user quits.
}


- (void)applicationWillEnterForeground:(UIApplication *)application {
    NSLog(@"进入活跃状态");
    // Called as part of the transition from the background to the active state; here you can undo many of the changes made on entering the background.
}


- (void)applicationDidBecomeActive:(UIApplication *)application {
    NSLog(@"恢复活跃状态");
    // Restart any tasks that were paused (or not yet started) while the application was inactive. If the application was previously in the background, optionally refresh the user interface.
}


- (void)applicationWillTerminate:(UIApplication *)application {
    NSLog(@"程序即将退出");
    // Called when the application is about to terminate. Save data if appropriate. See also applicationDidEnterBackground:.
}
- (UIInterfaceOrientationMask)application:(UIApplication *)application supportedInterfaceOrientationsForWindow:(UIWindow *)window {
    if (_isLandscape) {
//        NSLog(@"横屏");
        return UIInterfaceOrientationMaskLandscape;
    }
    else
    {
//        NSLog(@"竖屏");
        return UIInterfaceOrientationMaskPortrait;
    }
}

//Player.m
- (void)backToPortrait//回到竖屏
{
    NSLog(@"回到竖屏");
//    AppDelegate * appDelegate = (AppDelegate *)[UIApplication sharedApplication].delegate;
}

- (void)enterToLandscape//进入横屏
{
//    AppDelegate * appDelegate = (AppDelegate *)[UIApplication sharedApplication].delegate;
}

//作者：Fiona_L
//链接：http://www.jianshu.com/p/f917df3e3b2e
//來源：简书
//著作权归作者所有。商业转载请联系作者获得授权，非商业转载请注明出处。

@end
